
#include "Mapa.h"

Mapa::Mapa(){
	
	areas = NULL;

	mapWidth = mapHeight = 0;
}

bool Mapa::init(char* mapFile){

	std::ifstream file(mapFile);

	if( file.fail() || !file.good() )
		return false;

	while( file.peek() == ';' || file.peek() == '\n' )
		file.ignore(256,'\n');

	file >> mapName;

	while( file.peek() == ';' || file.peek() == '\n' )
		file.ignore(256,'\n');

	file >> std::skipws >> mapWidth;

	while( file.peek() == ';' || file.peek() == '\n' )
		file.ignore(256,'\n');

	file >> std::skipws >> mapHeight;

	if(mapWidth <= 0 || mapHeight <= 0)
		return false;

	while( file.peek() == ';' || file.peek() == '\n' )
		file.ignore(256,'\n');

	if(!initAreas())
		return false;

	for(int i=0; i< mapHeight; i++)
		for(int j=0; j< mapWidth; j++)
		{
			char areaFile[36];
			char realFile[45];

			file >> std::skipws >> areaFile;

			sprintf(realFile, "maps\\%s", areaFile);
			
			if(!areas[i][j].loadArea(realFile))
				return false;
		}

	return true;
}

bool Mapa::initAreas(){

	if(areas != NULL)
		return false;

	areas = new Area*[mapHeight];

	if(areas == NULL)
		return false;

	for(int i=0; i< mapHeight; i++)
		areas[i] = new Area[mapWidth];

	if(areas[mapHeight] == NULL)
		return false;

	return true;
}

void Mapa::loop(){
	for(int i=0; i< mapHeight; i++)
		for(int j=0; j< mapWidth; j++)
			areas[i][j].loop();
}

void Mapa::cleanup(){
	
	for(int i=0; i< mapHeight; i++)
		for(int j=0; j< mapWidth; j++)
			areas[i][j].cleanup();

	for(int i=0; i< mapHeight; i++)
		delete[] areas[i];

	delete[] areas;

	areas = NULL;
}
